package com.boil.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Created by ChenYong on 2016-11-23.
 * <br>
 * Spring 工具类。
 */
@Component
@Scope("singleton")
public class SpringUtils implements ApplicationContextAware {
    /**
     * 应用上下文
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    /**
     * 根据实例 ID 获取实例。
     *
     * @param beanId 实例 ID
     * @return 实例
     */
    public static Object getBean(String beanId) {
        return applicationContext.getBean(beanId);
    }

    /**
     * 根据实例类型获取实例。
     *
     * @param beanClass 实例类型
     * @return 实例
     */
    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    /**
     * 根据实例类型获取实例。
     *
     * @param beanId    实例 ID
     * @param beanClass 实例类型
     * @return 实例
     */
    public static <T> T getBean(String beanId, Class<T> beanClass) {
        return applicationContext.getBean(beanId, beanClass);
    }
}